package cn.dw.web.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.dw.domain.CheckInfo;
import cn.dw.domain.DutyInfo;
import cn.dw.domain.People;
import cn.dw.domain.Point;
import cn.dw.domain.WeChat;
import cn.dw.service.CheckInfoService;
import cn.dw.service.DutyInfoService;
import cn.dw.service.PeopleService;
import cn.dw.service.PointService;
import cn.dw.service.WeChatService;
import cn.dw.utils.QRCodeUtil;
import cn.dw.web.servlet.TokenThread;
import net.sf.json.JSONObject;

public class WeChatAction extends ActionSupport implements ModelDriven<WeChat> {
	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(WeChatAction.class);
	private static final long serialVersionUID = -7109377846601642920L;
	private WeChatService wcs;
	private WeChat wc = new WeChat();
	private ChangetoJson ctj = new ChangetoJson();
//	private static String AppId = "wx3542023ee690ee77";
//	private static String AppSecret = "24f082810558ac098fe21c2df1663904";
//	private static String AppId = "wx3542023ee690ee77";
//	private static String AppSecret = "24f082810558ac098fe21c2df1663904";
//	public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
//			+ AppId + "&secret=" + AppSecret;
	public static String access_token = "";
	private String menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	private String menu_urldel = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	private String result;
	private String openid;
	private PeopleService ps;
	private PointService pts;
	private DutyInfoService dis;
	private CheckInfoService cis;

//	public String getAppId() {
//		return AppId;
//	}
//
//	public void setAppId(String appId) {
//		AppId = appId;
//	}
//
//	public String getAppSecret() {
//		return AppSecret;
//	}
//
//	public void setAppSecret(String appSecret) {
//		AppSecret = appSecret;
//	}

	public void index() {
		String echostr = ServletActionContext.getRequest().getParameter(
				"echostr");
		if ((echostr == null) || (echostr.isEmpty())) {
			responseMsg();
		} else if (checkSignature()) {
			print(echostr);
		} else {
			print("error");
		}
	}

	@SuppressWarnings("unused")
	public void responseMsg() {
		String postStr = null;
		try {
			postStr = readStreamParameter(ServletActionContext.getRequest()
					.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if ((postStr != null) && (!postStr.isEmpty())) {
			Document document = null;
			try {
				document = DocumentHelper.parseText(postStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (document == null) {
				return;
			}
			Element root = document.getRootElement();
			String fromUsername = root.elementText("FromUserName");
			String toUsername = root.elementText("ToUserName");
			String event = root.elementText("Event");
			String key = root.elementText("EventKey");
			String keyword = root.elementTextTrim("Content");
		//	String MediaId = root.elementText("MediaId");
			String Format = root.elementText("Format");
			String msgtype = root.elementText("MsgType");
		//	String Recongnition = root.elementText("Recongnition");
			
			long time = new Date().getTime();
			
			if (msgtype.trim().equals("voice")) {
				String MediaId = root.elementText("MediaId");
				
				String MediaDowloadurl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
				
				MediaDowloadurl = MediaDowloadurl.replace("ACCESS_TOKEN",TokenThread.accessToken.getAccessToken());
					
				MediaDowloadurl = MediaDowloadurl.replace("MEDIA_ID", MediaId);
					
		//		System.out.println(MediaDowloadurl);
				
				try {
					keyword = BaiduVoice.dowloadfile(MediaDowloadurl);
				} catch (Exception e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				} 
				
			}
			
			
			if (msgtype.trim().equals("image")) {
				String MediaId = root.elementText("MediaId");
				
				String MediaDowloadurl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
				
				MediaDowloadurl = MediaDowloadurl.replace("ACCESS_TOKEN",TokenThread.accessToken.getAccessToken());
					
				MediaDowloadurl = MediaDowloadurl.replace("MEDIA_ID", MediaId);
				
				try {
					keyword = Faceplusplusapp.beauty(MediaDowloadurl);
				
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}
				
			}
			
			String textTpl = "<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[%4$s]]></MsgType><Content><![CDATA[%5$s]]></Content><FuncFlag>0</FuncFlag></xml>";

			String msgType = "text";
			String contentStr = "有什么可以帮您吗？";

			boolean states = false;
			if (keyword != null) {
			
				if (keyword.contains("天气")) {
					contentStr = weather.weatherByCity(keyword);
					states = true;
				} else if (keyword.equals("创建菜单")) {
					String res = menuUpdate();
					if (res.equals("success")) {
						contentStr = "创建成功";
						states = true;
					} else if (res.equals("error")) {
						contentStr = "创建失败";
						states = true;
					}
				} else if (keyword.contains("菜单")) {
					contentStr = "发送“菜单”可查看菜单；\n"
							+ "发送“地点+天气”可查看该地区当天的气候；\n"
							+ "发送"
							;
					states = true;
				} else if (keyword.contains("你的颜值")) {
					contentStr = keyword;
					states = true;
				}
			} else if ((event != null) && (event.equals("CLICK"))) {
				this.openid = fromUsername;
				if (key.equals("天气")) {
				//	contentStr = "你好";
				//	contentStr = weather.weatherString;
					states = true;
				} else {
					contentStr = "123";
					states = true;
				}
			} else if ((event != null) && (event.equals("subscribe"))) {
				contentStr = "您好，欢迎关注！体验生活，从这里开始！";
				states = true;
			} else if ((event != null) && (event.equals("SCAN"))) {
				contentStr = "您好，您已关注！";
				states = true;
			} else if ((event != null) && (event.equals("unsubscribe"))) {
				contentStr = "您好，您已取消关注！";
				states = true;
			} else if ((event != null) && (event.equals("VIEW"))) {
				this.openid = fromUsername;
				if (key.equals("http://wechatest00001.51vip.biz/system3/WeChat/login_in&out.html?ifin=1")) {
					this.openid = fromUsername;
					contentStr = "签到成功！";
				}
				if (key.equals("http://wechatest00001.51vip.biz/system3/WeChat/login_in&out.html?ifin=0")) {
					this.openid = fromUsername;
					contentStr = "签出成功！";
				}
				states = true;
			}
			String resultStr = String.format(textTpl, new Object[] {
					fromUsername, toUsername, time, msgType, contentStr });

			if (states) {
				try {
					resultStr = new String(resultStr.getBytes("UTF-8"),
							"ISO8859-1");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				print(resultStr);
				
				File file = null ;
				if(msgtype.trim().equals("voice")){
					file = new File("C:\\local\\123.amr");
				} else if (msgtype.trim().equals("image")) {
					file = new File("C:\\local\\123.jpg");
				}
				file.delete();
				
			}
		} else {
			print("请通过菜单使用网址导航服务！");
		}
	}

	public String sign() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");

		Integer ifin = new Integer(request.getParameter("ifin"));

		String code = request.getParameter("code");
		String codeurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		codeurl = codeurl.replace("APPID", TokenThread.getAppId());
		codeurl = codeurl.replace("SECRET", TokenThread.getAppSecret());
		codeurl = codeurl.replace("CODE", code);

		String myopenid = this.wcs.getOpenId(codeurl);

		this.openid = myopenid;

		String userOpenid = this.openid;

		Map<String, Object> map = new HashMap<>();

		List<People> peoples = this.ps.getAll();
		People peo = new People();
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				if (((People) peoples.get(i)).getOpenid().equals(userOpenid)) {
					peo = (People) peoples.get(i);
					if ((peo.getIfleader().intValue() == 4)
							|| (peo.getIfleader().intValue() == 2)) {
						if (ifin.intValue() == 1) {
							if (peo.getIfin().intValue() == 1) {
								map.put("msg", Integer.valueOf(3));
								break;
							}
							peo.setIfin(Integer.valueOf(1));

							DutyInfo dInfo = new DutyInfo();

							dInfo.setTimes(new Date());
							dInfo.setPeople(peo);
							this.ps.update(peo);
							this.dis.save(dInfo);
							map.put("msg", Integer.valueOf(1));
							break;
						}
						if (ifin.intValue() != 0) {
							break;
						}
						if (peo.getIfin().intValue() == 0) {
							map.put("msg", Integer.valueOf(4));
							break;
						}
						peo.setIfin(Integer.valueOf(0));

						List<DutyInfo> dInfos = this.dis.getAll();
						if (dInfos.size() > 0) {
							for (int j = dInfos.size() - 1; j >= 0; j--) {
								DutyInfo diInfo = (DutyInfo) dInfos.get(j);
								if ((diInfo.getPeople().getNumb() == peo
										.getNumb())
										&& (diInfo.getTimee() == null)) {
									diInfo.setTimee(new Date());

									this.dis.updata(diInfo);

									break;
								}
							}
						}
						this.ps.update(peo);
						map.put("msg", Integer.valueOf(2));
						break;
					}
					map.put("msg", Integer.valueOf(5));
					break;
				}
				map.put("msg", Integer.valueOf(0));
			}
		}
		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "sign";
	}

	public String register() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");

		String username = request.getParameter("username");
		String phone = request.getParameter("phone");

		String code = request.getParameter("code");

		String codeurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		codeurl = codeurl.replace("APPID", TokenThread.getAppId());
		codeurl = codeurl.replace("SECRET", TokenThread.getAppSecret());
		codeurl = codeurl.replace("CODE", code);

		String myopenid = this.wcs.getOpenId(codeurl);

		this.openid = myopenid;

		String userOpenid = this.openid;

		Map<String, Object> map = new HashMap<>();
		People peo = new People();

		List<People> peoples = this.ps.getAll();
		int count = 0;
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				if (((People) peoples.get(i)).getOpenid().equals(userOpenid)) {
					count++;
				}
			}
		}
		if (count != 0) {
			map.put("info", Boolean.valueOf(false));
		} else if (count == 0) {
			peo.setName(username);
			peo.setPhone(phone);
			peo.setOpenid(userOpenid);
			peo.setLevel(Integer.valueOf(2));
			peo.setIfleader(Integer.valueOf(0));
			peo.setPoint(null);
			peo.setIfin(Integer.valueOf(0));
			this.ps.save(peo);

			map.put("info", Boolean.valueOf(true));
		}
		JSONObject json = JSONObject.fromObject(map);
		this.result = json.toString();
		return "regist";
	}

	public String message_set() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");

		String name = request.getParameter("name");
		String addr = request.getParameter("addr");
		Double lng = new Double(request.getParameter("lng"));
		Double lat = new Double(request.getParameter("lat"));

		String code = request.getParameter("code");

		String codeurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		codeurl = codeurl.replace("APPID", TokenThread.getAppId());
		codeurl = codeurl.replace("SECRET", TokenThread.getAppSecret());
		codeurl = codeurl.replace("CODE", code);

		String myopenid = this.wcs.getOpenId(codeurl);

		this.openid = myopenid;

		String userOpenid = this.openid;

		Map<String, Object> map = new HashMap<>();

		List<People> peoples = this.ps.getAll();

		People peo = new People();

		boolean ifwe = true;
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				if (((People) peoples.get(i)).getOpenid().equals(userOpenid)) {
					peo = (People) peoples.get(i);
					ifwe = true;
					break;
				}
				ifwe = false;
			}
		}
		if (ifwe) {
			Point point = new Point();

			point.setAddr(addr);
			point.setName(name);
			point.setLng(lng);
			point.setLat(lat);

			this.pts.save(point);

			peo.setIfleader(Integer.valueOf(1));
			peo.setPoint(point);

			this.ps.update(peo);

			String poid = point.getId().toString();

			QRCodeUtil qc = new QRCodeUtil();

			String QRimgpath = qc.QRbuild(poid);

			point.setImgurl(QRimgpath);

			this.pts.update(point);

			map.put("msg", Boolean.valueOf(true));
		} else {
			map.put("msg", Boolean.valueOf(false));
		}
		JSONObject json = JSONObject.fromObject(map);
		this.result = json.toString();
		return "message_set";
	}

	public String mymessage() throws Exception {
		Map<String, Object> map = new HashMap<>();

		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");

		String code = request.getParameter("code");

		String codeurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

		codeurl = codeurl.replace("APPID", TokenThread.getAppId());
		codeurl = codeurl.replace("SECRET", TokenThread.getAppSecret());
		codeurl = codeurl.replace("CODE", code);

		String myopenid = this.wcs.getOpenId(codeurl);

		this.openid = myopenid;

		String userOpenid = this.openid;

		List<People> peoples = this.ps.getAll();

		People peo = new People();

		boolean ifwe = true;
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				if (((People) peoples.get(i)).getOpenid().equals(userOpenid)) {
					peo = (People) peoples.get(i);
					ifwe = true;
					break;
				}
				ifwe = false;
			}
		}
		List<People> peoples2 = new ArrayList<>();
		if (ifwe) {
			map.put("mynumb", peo.getNumb());
			map.put("people", peo.getName());
			map.put("phone", peo.getPhone());
			map.put("ifleader", peo.getIfleader());
			if (peo.getPoint() == null) {
				map.put("pointname", "");
				map.put("addr", "");
				map.put("qrimg", "");
			} else {
				map.put("pointname", peo.getPoint().getName());
				map.put("addr", peo.getPoint().getAddr());
				map.put("qrimg", peo.getPoint().getImgurl());
				peoples2 = this.ps.getByPointId(peo.getPoint().getId());

				List<People> peoples3 = new ArrayList<>();
				List<People> peoples4 = new ArrayList<>();
				if (peoples2.size() > 0) {
					for (int i = 0; i < peoples2.size(); i++) {
						if (((People) peoples2.get(i)).getLevel().intValue() == 1) {
							map.put("leadername",
									((People) peoples2.get(i)).getName());
						} else if (((People) peoples2.get(i)).getLevel()
								.intValue() == 2) {
							People peo2 = new People();
							if (((People) peoples2.get(i)).getIfleader()
									.intValue() == 3) {
								peo2 = (People) peoples2.get(i);
								peoples3.add(peo2);
							} else if (((People) peoples2.get(i)).getIfleader()
									.intValue() == 4) {
								peo2 = (People) peoples2.get(i);
								peoples4.add(peo2);
							}
						}
					}
				}
			}
			map.put("msg", Boolean.valueOf(true));
		} else {
			map.put("msg", Boolean.valueOf(false));
		}
		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "mymessage";
	}

	public String memberrow() throws Exception {
		String userOpenid = this.openid;

		List<People> peoples = this.ps.getAll();

		People peo = new People();

		boolean ifwe = true;
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				if (((People) peoples.get(i)).getOpenid().equals(userOpenid)) {
					peo = (People) peoples.get(i);
					ifwe = true;
					break;
				}
				ifwe = false;
			}
		}
		List<Map<String, Object>> list = new ArrayList<>();
		if (ifwe) {
			List<People> peoples2 = this.ps
					.getByPointId(peo.getPoint().getId());
			if (peoples2.size() > 0) {
				for (int i = 0; i < peoples2.size(); i++) {
					Map<String, Object> map = new HashMap<>();
					if (((People) peoples2.get(i)).getLevel().intValue() == 2) {
						People peo2 = new People();
						if (((People) peoples2.get(i)).getIfleader().intValue() == 4) {
							peo2 = (People) peoples2.get(i);
							map.put("name", peo2.getName());
							map.put("numb", peo2.getNumb());
							list.add(map);
						}
					}
				}
			}
		} else {
			Map<String, Object> map = new HashMap<>();
			map.put("msg", Boolean.valueOf(false));
		}
		this.ctj.json(list);

		return null;
	}

	public String membernew() throws Exception {
		String userOpenid = this.openid;

		List<People> peoples = this.ps.getAll();

		People peo = new People();

		boolean ifwe = true;
		if (peoples.size() > 0) {
			for (int i = 0; i < peoples.size(); i++) {
				if (((People) peoples.get(i)).getOpenid().equals(userOpenid)) {
					peo = (People) peoples.get(i);
					ifwe = true;
					break;
				}
				ifwe = false;
			}
		}
		List<Map<String, Object>> list = new ArrayList<>();
		if (ifwe) {
			List<People> peoples2 = this.ps
					.getByPointId(peo.getPoint().getId());
			if (peoples2.size() > 0) {
				for (int i = 0; i < peoples2.size(); i++) {
					Map<String, Object> map = new HashMap<>();
					if (((People) peoples2.get(i)).getLevel().intValue() == 2) {
						People peo2 = new People();
						if (((People) peoples2.get(i)).getIfleader().intValue() == 3) {
							peo2 = (People) peoples2.get(i);
							map.put("name", peo2.getName());
							map.put("numb", peo2.getNumb());
							list.add(map);
						}
					}
				}
			}
		} else {
			Map<String, Object> map = new HashMap<>();
			map.put("msg", Boolean.valueOf(false));
		}
		this.ctj.json(list);
		return null;
	}

	public String check_replay() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");

		Map<String, Object> map = new HashMap<>();

		String code = request.getParameter("code");

		System.out.println(code);
		Integer checkInfoId = new Integer(request.getParameter("checkInfoId"));
		Double lng = new Double(request.getParameter("lng"));
		Double lat = new Double(request.getParameter("lat"));

		CheckInfo checkInfo = this.cis.getById(checkInfoId);

		People people = this.ps.getById(checkInfo.getPeople().getNumb());

		Point point = this.pts.getById(people.getPoint().getId());

		IfState ifState = new IfState();

		String state = null;
		if (!checkInfo.isReply()) {
			state = "异常";
		} else {
			state = ifState.State(point.getLng(), point.getLat(),
					checkInfo.getLongitude(), checkInfo.getLatitude(),
					checkInfo.getDate(), checkInfo.getReplydate());
		}
		if (state.equals("正常")) {
			map.put("msg", Boolean.valueOf(true));
		} else if (state.equals("异常")) {
			checkInfo.setLatitude(lat);
			checkInfo.setReply(true);
			checkInfo.setLongitude(lng);
			checkInfo.setReplydate(new Date());

			this.cis.updata(checkInfo);

			map.put("msg", Boolean.valueOf(true));
		} else {
			map.put("msg", Boolean.valueOf(false));
		}
		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "check_replay";
	}

	public String menuUpdate() {
		String accessToken = TokenThread.accessToken.getAccessToken();

		this.wcs.menuDelete(accessToken, this.menu_urldel);
		String msg = this.wcs.menuCreate(accessToken, this.menu_url);
		if ("0ok".equals(msg)) {
			return "success";
		}
		return "error";
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000L);
	}

	public String webweixin() throws Exception {
		String accessToken = TokenThread.accessToken.getAccessToken();

		HttpServletRequest request = ServletActionContext.getRequest();

		request.setCharacterEncoding("utf-8");

		String ticketurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				+ accessToken + "&type=jsapi";

		Map<String, Object> map = new HashMap<>();

		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String ticket = this.wcs.getTicket(ticketurl);

		String url = request.getParameter("url");

		url = URLDecoder.decode(url, "UTF-8");

		String signature = "";
		String string1 = "jsapi_ticket=" + ticket + "&noncestr=" + nonce_str
				+ "&timestamp=" + timestamp + "&url=" + url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			byte[] digest = crypt.digest(string1.toString().getBytes());
			signature = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		map.put("url", url);
		map.put("nonceStr", nonce_str);
		map.put("timestamp", timestamp);
		map.put("signature", signature);
		map.put("jsapi_ticket", ticket);
		map.put("appId", "wx3542023ee690ee77");
		map.put("msg", Integer.valueOf(1));

		JSONObject json = JSONObject.fromObject(map);

		this.result = json.toString();

		return "sign";
	}

	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest = strDigest + byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
				'b', 'c', 'd', 'e', 'f' };

		char[] tempArr = new char[2];

		tempArr[0] = Digit[(mByte >>> 4 & 0xF)];

		tempArr[1] = Digit[(mByte & 0xF)];

		String s = new String(tempArr);

		return s;
	}

	public WeChat getWc() {
		return this.wc;
	}

	public void setWc(WeChat wc) {
		this.wc = wc;
	}

	public void setWcs(WeChatService wcs) {
		this.wcs = wcs;
	}

	public boolean checkSignature() {
		String signature = ServletActionContext.getRequest().getParameter(
				"signature");
		String timestamp = ServletActionContext.getRequest().getParameter(
				"timestamp");
		String nonce = ServletActionContext.getRequest().getParameter("nonce");
		String token = "nnnl";
		String[] tmpArr = { token, timestamp, nonce };
		Arrays.sort(tmpArr);
		String tmpStr = ArrayToString(tmpArr);
		tmpStr = SHA1Encode(tmpStr);
		if (tmpStr.equalsIgnoreCase(signature)) {
			return true;
		}
		return false;
	}

	public void print(String content) {

		try {
			ServletActionContext.getResponse().getWriter().print(content);
			ServletActionContext.getResponse().getWriter().flush();
			ServletActionContext.getResponse().getWriter().close();
		} catch (Exception localException) {
		}
	}

	public String ArrayToString(String[] arr) {
		StringBuffer bf = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			bf.append(arr[i]);
		}
		return bf.toString();
	}

	public String SHA1Encode(String sourceString) {
		String resultString = null;
		try {
			resultString = new String(sourceString);
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			resultString = byte2hexString(md.digest(resultString.getBytes()));
		} catch (Exception localException) {
		}
		return resultString;
	}

	public final String byte2hexString(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xFF) < 16) {
				buf.append("0");
			}
			buf.append(Long.toString(bytes[i] & 0xFF, 16));
		}
		return buf.toString().toUpperCase();
	}

	public String readStreamParameter(ServletInputStream in) {
		StringBuilder buffer = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buffer.toString();
	}

	public WeChatService getWcs() {
		return this.wcs;
	}

	public void setWc(WeChatService wcs) {
		this.wcs = wcs;
	}

	public WeChat getModel() {
		return this.wc;
	}

	public String getResult() {
		return this.result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setPs(PeopleService ps) {
		this.ps = ps;
	}

	public void setPts(PointService pts) {
		this.pts = pts;
	}

	public void setCis(CheckInfoService cis) {
		this.cis = cis;
	}

	public void setDis(DutyInfoService dis) {
		this.dis = dis;
	}
}
